import { assetsDB } from '@/indexDB/index'
import { ref } from 'vue'
import { num3 } from '@/utils/num'

export const usePressure = () => {

  const totalPressure = ref(0)
  const updateTotalPressure = async (netId?: string | number) => {
    let query = assetsDB.netList.where('id').above(0)
    if (netId) {
      query = query.filter(net => net.id !== netId)
    }
    const list = await query.toArray()
    totalPressure.value = list.reduce((lastTotal, curNet) => {
      const { totalPressure } = curNet

      return +totalPressure + lastTotal
    }, 0)
  }

  updateTotalPressure()


  const moneyNum = ref(0)

  const getMoneyNum = async () => {
    const list = await assetsDB.holdList.where('type').equals('currency').toArray()
    moneyNum.value = list.reduce((preTotal, curHold) => {
      const { holdValue } = curHold
      return num3(holdValue).add(preTotal).value
    }, 0)
  }

  getMoneyNum()

  const getPressureInfo = (totalPressure: number) => {
    const left = num3(moneyNum.value).subtract(totalPressure).value
    let colorType = 'success'
    if (left >= 20000) {
      colorType = 'success'
    }
    if (left >= 5000) {
      colorType = 'warning'
    }
    if (left < 5000) {
      colorType = 'danger'
    }
    return {
      left,
      color: `var(--el-color-${colorType})`
    }
  }

  return {
    totalPressure,
    moneyNum,
    updateTotalPressure,
    getPressureInfo
  }
}